package com.glodon.paas.activity.util;

import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.Log4JLogChute;

import com.glodon.paas.activity.api.bean.Activity;
import com.glodon.paas.activity.dao.domain.ActivityEntity;

public class ActivityTemplateMerger {

    private static VelocityEngine velocityEngine;

    public static VelocityEngine getEngine() {
        if (velocityEngine == null) {
            velocityEngine = new VelocityEngine();
            velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                                       "org.apache.velocity.runtime.log.Log4JLogChute");
            velocityEngine.setProperty(Log4JLogChute.RUNTIME_LOG_LOG4J_LOGGER,
                                       "activityTemplate");
            velocityEngine.init();
        }
        return velocityEngine;
    }

    public static String mergeTemplate(Activity entity, String template) {
        StringWriter writer = new StringWriter();
        VelocityContext context = VelocityContextWrapActivity.wrap(entity);
        // Velocity.evaluate(context, writer, "ActivityTemplate", template);
        getEngine().evaluate(context, writer, "ActivityTemplate", template);
        return writer.toString();
    }

    public static String mergeTemplate(ActivityEntity entity, String template) {
        StringWriter writer = new StringWriter();
        VelocityContext context = VelocityContextWrapActivity.wrap(entity);
        // Velocity.evaluate(context, writer, "ActivityTemplate", template);
        getEngine().evaluate(context, writer, "ActivityTemplate", template);
        return writer.toString();
    }
}
